import { reqLogin, reqGetUserStatus, reqLogout } from '@/apis/user.js';
import { reqTotalCount } from '@/apis/rexiaogoods.js';
import { setToken, setStatus, getToken, getStatus, removeToken, removeUserInfo, removeStatus } from '@/utils/auth.js';
const state = {
	token: getToken(),
	userInfo: {},
	permissionStatus: getStatus() // 0 未审核 1 审核通过 2 审核失败 3 未提交 4 未登录
};
const actions = {
	// 登录
	async userLogin({ dispatch, commit }, userInfo) {
		let res = await reqLogin(userInfo);
		if (res.code === 200) {
			// 存储一下token
			commit('USER_LOGIN', res.data.token);
			// 初始化购物车总数
			dispatch('getCarTotal');
			dispatch('getUserStatus');
			return res;
		}
	},
	async getCarTotal(context) {
		let res = await reqTotalCount();
		if (res.code === 200) {
			context.dispatch('car/addToCar', res.data, { root: true });
		}
	},
	async getUserStatus(context) {
		let res = await reqGetUserStatus();
		if (res.code === 200) {
			context.commit('USER_STATUS', res.data.status);
			if(res.data.status == '4'){
				context.dispatch('car/addToCar', {total:0,size:0}, { root: true });// token过期清空购物车角标
				context.dispatch('car/addActivedList', [], { root: true });
			}
			return res;
		}
	},
	// async userInfo({ commit }) {
	//   let res = await reqUserInfo();
	//   if (res.code == 200) {
	//     // 存一下
	//     commit('USER_INFO', res.data);
	//     return 'OK';
	//   }else {
	//     return Promise.reject(new Error(res.message));
	//   }
	// },
	async userLogout(context) {
		let res = await reqLogout();
		if (res.code == 200) {
			// commit('USER_LOGOUT');
			removeToken();
			removeStatus();
			context.dispatch('car/addToCar', {total: 0,size: 0},{ root: true });
			context.dispatch('getUserStatus');
			uni.removeStorageSync('customerPhone');
			return res;
		}
	}
};
const mutations = {
	USER_LOGIN(state, token) {
		state.token = token;
		// 持久化存储
		setToken(token);
	},
	USER_STATUS(state, status) {
		state.permissionStatus = status;
		setStatus(status);
	}
	// USER_INFO(state, userInfo) {
	//   state.userInfo = userInfo;
	// },
};
const getters = {
	userInfo(state) {
		return state.userInfo || {};
	},
	permissionStatus(state) {
		return state.permissionStatus || '-1';
	}
};
export default {
	namespaced: true,
	actions,
	mutations,
	state,
	getters
};
